package com.check.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.check.dao.PersonDao;
import com.check.dao.PersonRoleDao;
import com.check.pojo.Opr;
import com.check.service.PersonRoleService;
import com.check.service.PersonService;

@Service("personRoleService")
public class PersonRoleServiceImpl implements PersonRoleService{

	@Autowired
	@Qualifier("personRoleDao")
	private PersonRoleDao personRoleDao;
	
	@Autowired
	@Qualifier("personDao")
	private PersonDao personDao;
	
	public Opr findRoleByOprId(String oprId) {
		Opr opr=null;
		try {
			opr=personRoleDao.findRoleByOprId(oprId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return opr;
	}

	public boolean updatePersonRole(Opr opr) {
		boolean flag=false;
		try {
			String oprId=opr.getOprId();
			String[] orgIds = opr.getOrgIds();
			personRoleDao.deletePersonRole(oprId);
			personRoleDao.deletePersonDept(oprId);
			personRoleDao.insertPersonRole(opr);
			personRoleDao.updatePersonOpr(opr);
			for (String orgId : orgIds) {
				Opr newOpr=new Opr();
				newOpr.setOprId(oprId);
				newOpr.setOrgId(orgId);
				personRoleDao.insertPersonOrg(newOpr);
				
			}
			flag=true;
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			flag=false;
		}
		return flag;
	}

	public boolean deletePersonRole(String oprId) {
		boolean flag=false;
		try {
			personRoleDao.deletePersonDept(oprId);
			personRoleDao.deletePersonRole(oprId);
			personDao.deleteOpr(oprId);
			flag=true;
			
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			flag=false;
			
		}
		return flag;
	}
	
	public boolean insertPersonRole(Opr opr) {
		boolean flag=false;
		try {
			String oprId=opr.getOprId();
			String[] orgIds = opr.getOrgIds();
			
			personRoleDao.insertPersonRole(opr);
			personRoleDao.insertPersonOpr(opr);
			for (String orgId : orgIds) {
				Opr newOpr=new Opr();
				newOpr.setOprId(oprId);
				newOpr.setOrgId(orgId);
				personRoleDao.insertPersonOrg(newOpr);
				
			}
			flag=true;
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			flag=false;
		}
		return flag;
	}

}
